/*  Copyright (c) 2003 PureSilk.Org  */
/* ====================================================================
 * 
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights 
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:  
 *       "This product includes software developed by the 
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written 
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */ 


/*
 * RARServlet.java
 *
 * Created on November 3, 2002, 9:37 PM
 */
 
package org.puresilk.base;           

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/** 
 *
 * @author  david
 * @version 
 */
public abstract class PSOServlet extends HttpServlet {
	private static final long serialVersionUID = 6486518553983131467L;
	protected Properties props = new Properties();
    private boolean sqlEnabled = false;
    
    protected int logMessageDefaultLevel = 1;
    protected int logLevel = 0;
    protected String servletName = "PSOServlet";
    
    public static final int LOG_DEBUG_MSG = 0;
    public static final int LOG_INFO_MSG = 1;
    public static final int LOG_WARN_MSG = 2;
    public static final int LOG_ERROR_MSG = 3;
    public static final int LOG_FATAL_MSG = 4;
    
    /** 
     * Initializes the servlet and prep for DB services.
    */  
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        
        //--------------------------------------------------
        // To get the database services we need to find the 
        // correct properties file.  Then we can retrieve 
        // the database information from the properties.  
        // Then we find the Connection Manager and join the 
        // connection pool for the application database.
        
        String propFile = config.getInitParameter("properties");
        
        // adjust for relative path (if needed)
        if ( !propFile.startsWith("/") ) {
        	// location defaults to application WEB-INF
        	StringBuffer pPath = new StringBuffer(config.getServletContext().getRealPath("/WEB-INF"))
        												. append("/") .append(propFile);
        	propFile = pPath.toString();											
        }
        
        try {
            // load up the application parameters
            props.load(new FileInputStream(propFile));
     
            logDebugMsg ("PSOServlet Properties Loaded.");
            
            // set logging characteristics
            if ( !"".equals(props.getProperty("LogMessageDefaultLevel","") ) )
                logMessageDefaultLevel = Integer.parseInt(props.getProperty("LogMessageDefaultLevel"));
                
            if ( !"".equals(props.getProperty("LogLevel","") ) )
                logLevel = Integer.parseInt(props.getProperty("LogLevel"));
  
            logDebugMsg ("PSOServlet Logging initialized.");
 
        }
        catch (Exception ex) {
            // may have been in logging system, so go low...
            log(" Error loading servlet properties",ex);
        }

    }

    /** Destroys the servlet.
    */  
    public void destroy() {

    }

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected abstract void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException ;
    
    /** Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    } 

    /** Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Actually just a shell to provide a common base class.";
    }
    

    //--------------------------------------------------------
    // common servlet needs
    
    /** get an init property */
    protected String getProperty ( String propName ) {
        String rv = null;
        if (props.containsKey( propName) ) 
            rv = (String)props.get(propName);
        return rv;
    }
            
    /** check to see if this servlet is attached to a database */
    protected boolean isSqlEnabled() { 
    	return sqlEnabled; 
    }
    
    /** run a JSP Page */
    protected void sendToJSP(String jsp, HttpServletRequest req, HttpServletResponse resp) {
        try{
            RequestDispatcher rd = getServletContext().getRequestDispatcher(jsp);
            rd.forward(req,resp);
            
            logDebugMsg("Dispatched JSP: " + jsp);
        }
        catch (Exception ex) {
            logErrorMsg("Error Dispatching JSP: " + ex.getMessage());
        }
    }
    
    
    //----------------------------
    // universal logger utility
    
    /** log message writer */
    synchronized protected void logger ( String message ) {
        // pass to servlet logger for now
        log(message);
    }
    
    
    /** Default logging mechanism */
    protected void logMsg ( String message ) {
        logMsg(message, logMessageDefaultLevel);
    }

    /** log message formatter */
    protected void logMsg ( String message, int level ) {
        // range check
        if ( level >= logLevel ) {
            // format the message
            StringBuffer msg = new StringBuffer("<").append(servletName).append("::");
            String levelText = "";
            switch ( level ) {
                case LOG_DEBUG_MSG:
                    levelText = "Debug";
                    break;
                case LOG_INFO_MSG:
                    levelText = "Info";
                    break;
                case LOG_WARN_MSG:
                    levelText = "Warning";
                    break;
                case LOG_ERROR_MSG:
                    levelText = "Error";
                    break;
                case LOG_FATAL_MSG:
                    levelText = "Fatal Error";
            }
            
            // complete the message
            msg.append ( levelText )
               .append ( "> " )
               .append ( message );
            
            // formating done, send to logger
            logger ( msg.toString() );
        }
    }
    
    /** Debug util */
    public void logDebugMsg( String message ) {
        logMsg( message, LOG_DEBUG_MSG );
    }
    /** Info util */
    public void logInfoMsg( String message ) {
        logMsg( message, LOG_INFO_MSG );
    }
    /** Warning util */
    public void logWarningMsg( String message ) {
        logMsg( message, LOG_WARN_MSG );
    }
    /** Error util */
    public void logErrorMsg( String message ) {
        logMsg( message, LOG_ERROR_MSG );
    }
    /** Fatal Error util */
    public void logFatalMsg( String message ) {
        logMsg( message, LOG_FATAL_MSG );
    }
 }
